import java.text.SimpleDateFormat
import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

log.info "start"

String message = request.getParameter("message")
String gmail = request.getParameter("gmail")

String authToken = getAuthToken()
log.info "authToken "+authToken
def registrationIds = getRegistrationId(gmail)
log.info "slut  dfhfgh "
registrationIds.each {
	log.info "authToken: "+ authToken
	sendMessage(authToken,it.registration_id,message)
}
log.info "slut "
//"APA91bGEU_RSHUREnm1is_f5zN46kKBO5b3P0xgilSZcGXk5MXNTLFpLjAlze9yp474haZKHHc4ELVf8QLqGhJRsAvLBNOx1P2c66SQpPFxE8LhH1azqhHCVNxF8BX3SJF8SmOOGUTId"
//authToken = authToken - "SID="

String result = "Message sent, hope it helps!";
request.setAttribute 'result', result
forward '/WEB-INF/pages/index.gtpl'



public static String sendMessage(String authToken, String registrationId, String message) {
    try {
		if (message) {
			message = URLEncoder.encode(message, "UTF-8")
		} 
        URL url = new URL("http://android.apis.google.com/c2dm/send");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

        String postBody = "registration_id="+registrationId+"&collapse_key=LOST&data.message="+message

        writer.write(postBody);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            println "response: " + connection.responseMessage
            InputStreamReader reader = new InputStreamReader(connection.content)
            BufferedReader bR = new BufferedReader(reader)
            String line;
            while((line = bR.readLine()) != null) {
                println line
            }
        } else {
            println "responseCode: " + connection.responseCode
        }
    } catch (MalformedURLException e) {
        println "MalformedURLException" + e
    } catch (IOException e) {
        println "IOException " + e
    }
    return "ho"

}


public def getRegistrationId(String gmail) {

	def query = new Query("user")
	query.addFilter("gmail", Query.FilterOperator.EQUAL, gmail)
	PreparedQuery preparedQuery = datastore.prepare(query)
	def registrationIds = preparedQuery.asList(withLimit(10))
	return registrationIds
}


public static String getAuthToken() {
    try {
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        //Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
        String postBody = '''Email=tribe.vilt@gmail.com&Passwd=LostTribe21&accountType=HOSTED_OR_GOOGLE&source=vilt-lost-1&service=ac2dm'''
        
        
        writer.write(postBody);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            println "response: " + connection.responseMessage
            InputStreamReader reader = new InputStreamReader(connection.content)
            BufferedReader bR = new BufferedReader(reader)
            String line;
            String content = ""
            while((line = bR.readLine()) != null) {
                if (line.startsWith("Auth=")) {
                    content = line - "Auth="
                }
            }
            return content
        } else {
            println "responseCode: " + connection.responseCode
        }
    } catch (MalformedURLException e) {
        println "MalformedURLException" + e
    } catch (IOException e) {
        println "IOException " + e
    }
    return null
}















